<template >
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 点击首页会跳转到home -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区 -->
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddSort">添加分类</el-button>
        </el-col>
      </el-row>

      <!--  表格 -->
      <tree-table
        class="treeTable"
        :data="cateList"
        :columns="columns"
        show-index
        :selection-type="false"
        :expand-type="false"
      >
        <template slot="isok" scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color:lightgreen"></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <template slot="isok2" scope="scope">
          <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" v-else-if="scope.row.cat_level===2">三级</el-tag>
        </template>

        <template slot="isok3" scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEdit(scope.row.cat_id)"
          >修改</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteById(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 展示添加分类显示框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="dialogVisibleShowAddSort"
      width="50%"
      @close="dialogVisibleShowAddSortclose"
    >
      <el-form :model="addCateForm" :rules="addCateRules" ref="addCateRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_id">
          <el-input v-model="addCateForm.cat_id"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options用来指定数据源 -->
          <!-- props用来指定级联配置选项 -->
          <!-- v-model里面一定是数组，因为又可能要保存多个ID -->
          <el-cascader
            v-model="parentId"
            :options="parentList"
            :props="parentProps"
            @change="parentCateChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleShowAddSort=false">取 消</el-button>
        <el-button type="primary" @click="addParentCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 展示修改分类显示框 -->
    <el-dialog title="修改分类" :visible.sync="dialogVisibleShowEdit" width="50%" @close="closeEdit">
      <el-form :model="editCateForm" :rules="editRules" ref="editRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleShowEdit=false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //添加商品分类的数据对象
      addCateForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0
      },
      //修改分类表单
      editCateForm: {},
      //父级数据源列表
      parentList: [],
      //级联配置
      parentProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true
      },
      parentId: [],
      //验证规则
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      //验证规则
      editRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      cateList: [],
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      // 为table指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",

          type: "template",
          template: "isok"
        },
        {
          label: "排序",

          type: "template",
          template: "isok2"
        },
        {
          label: "操作",

          type: "template",
          template: "isok3"
        }
      ],
      dialogVisibleShowAddSort: false,
      dialogVisibleShowEdit: false
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获得商品列表数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) {
        return;
      } else {
        this.cateList = res.data.result;
        //为总数据条数赋值
        this.total = res.data.total;
      }
    },
    //监听pagesize变化
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getCateList();
    },
    //监听pagenum变化
    handleCurrentChange(newnum) {
      this.queryInfo.pagenum = newnum;
      this.getCateList();
    },
    //显示添加分类对话框
    showAddSort() {
      this.getParentList();
      this.dialogVisibleShowAddSort = true;
    },
    //获取父级数据列表
    async getParentList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: [2] }
      });
      if (res.meta.status !== 200) {
        return;
      } else {
        this.parentList = res.data;
      }
    },
    //监听双向绑定中ID的变化
    //如果parentId的length大于0，说明选中了父级分类，反之没有选中
    parentCateChange() {
      console.log(this.parentId);
      if (this.parentId.length > 0) {
        this.addCateForm.cat_pid = this.parentId[this.parentId.length - 1];
        this.addCateForm.cat_level = this.parentId.length;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    //点击确定后调用API添加父级
    addParentCate() {
      this.$refs.addCateRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await this.$http.post(
            "categories",
            this.addCateForm
          );
          if (res.meta.status !== 201) {
            return this.$message.error("添加分类失败");
          } else {
            this.$message.success("添加分类成功");
            this.getCateList();
            this.dialogVisibleShowAddSort = false;
          }
        }
      });
    },
    //关闭添加分类窗口后重置表单数据
    dialogVisibleShowAddSortclose() {
      this.$refs.addCateRef.resetFields();
      this.parentId = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    //点击修改分类后加载数据到表单上
    async showEdit(id) {
      const { data: res } = await this.$http.get("categories/" + id);
      if (res.meta.status !== 200) {
        return;
      } else {
        this.editCateForm = res.data;
        this.dialogVisibleShowEdit = true;
      }
    },
    //重置预验证的提示
    closeEdit() {
      this.$refs.editRef.resetFields();
    },
    //点击确定预验证后更改分类
    edit() {
      this.$refs.editRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await this.$http.put(
            "categories/" + this.editCateForm.cat_id,
            { cat_name: this.editCateForm.cat_name }
          );
          if (res.meta.status !== 200) {
            return this.$message.error("修改分类失败");
          } else {
            this.dialogVisibleShowEdit = false;
            this.$message.success("修改分类成功");
            this.getCateList();
          }
        }
      });
    },
    //根据ID删除分类
    async deleteById(id) {
      const result = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);
      if (result !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        const { data: res } = await this.$http.delete("categories/" + id);
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败");
        } else {
          this.$message.success("删除成功");

          this.getCateList();
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>